//
//  STMGoodsPublishViewController.m
//  StoreManagement
//
//  Created by centling on 16/6/7.
//  Copyright © 2016年 alfred. All rights reserved.
//

#import "STMGoodsPublishViewController.h"
#import "GYLAddImage.h"
#import "STMLoginViewController.h"

@interface STMGoodsPublishViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITextField *goodsNameTf;
@property (weak, nonatomic) IBOutlet UILabel *goodsCateLabel;
@property (weak, nonatomic) IBOutlet UITextField *goodsPriceTf;
@property (weak, nonatomic) IBOutlet UITextField *marketPriceTf;
@property (weak, nonatomic) IBOutlet UITextField *goodsStoreTf;
@property (weak, nonatomic) IBOutlet UITextField *goodsFreightTf;
@property (weak, nonatomic) IBOutlet UITextField *goodsDescriptionTf;
@property (weak, nonatomic) IBOutlet UIButton *submitButton;
@property (nonatomic, strong) GYLAddImage *addImageView;

@property (nonatomic, strong) UITableView *cateTableView;
@property (nonatomic, strong) NSMutableArray *cateArray;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, copy) NSString *selectgcId;
@property (nonatomic, copy) NSString *selectgcName;
@property (nonatomic, copy) NSString *uploadImages;

@end


@implementation STMGoodsPublishViewController

-(UIView *)maskView{
    if (!_maskView) {
        _maskView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
        _maskView.backgroundColor=[UIColor blackColor];
        _maskView.alpha=0;
        UIGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cateTableViewDisappear)];
        [_maskView addGestureRecognizer:tap];
    }
    return _maskView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MAINGRAYCOLOR;
    self.addImageView = [[GYLAddImage alloc] initWithFrame:CGRectMake(0, 99, SCREEN_W, 65)];
    __weak typeof(self) weakSelf = self;
    _addImageView.block = ^(UIViewController *pickerVC){
        [weakSelf presentViewController:pickerVC animated:YES completion:nil];
    };
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showCateTableView)];
    self.goodsCateLabel.userInteractionEnabled = YES;
    [self.goodsCateLabel addGestureRecognizer:tap];
    [self.view addSubview:self.addImageView];
    
    [self.submitButton addTarget:self action:@selector(submitButtonClick) forControlEvents:UIControlEventTouchUpInside];
}



- (void)showCateTableView {

    self.cateTableView = [[UITableView alloc] initWithFrame:CGRectMake(40, SCREEN_H/2-100, SCREEN_W-80, 200)];
    self.cateTableView.delegate = self;
    self.cateTableView.dataSource = self;
    self.cateTableView.rowHeight = 35;
    [self.cateTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellID"];
    [[[UIApplication sharedApplication] delegate].window addSubview:self.cateTableView];
    [([UIApplication sharedApplication].delegate).window insertSubview:self.maskView belowSubview:self.cateTableView];
    self.maskView.alpha = 0.4;
    [STMNetworkAPI getGoodsCategoryWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                   success:^(STMGoodsCategoryModel *result) {
                                       if ([result.code isEqualToString:@"200"]) {
                                           self.cateArray = [NSMutableArray arrayWithArray:result.result];
                                           [self.cateTableView reloadData];
                                       } else if ([result.code isEqualToString:@"401"]) {
                                           [GlobalUtil presentLoginVC];
                                       } else {
                                           [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                       }
                                   }
                                   failure:^(NSError *err) {
                                       [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                   }];
}


- (void)cateTableViewDisappear {
    [self.cateArray removeAllObjects];
    self.selectgcName = @"";
    [self.maskView removeFromSuperview];
    self.maskView = nil;
    [self.cateTableView removeFromSuperview];
    self.cateTableView = nil;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cateArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    STMGoodsCategoryDetail *cateDetail = self.cateArray[indexPath.row];
    cell.textLabel.text = cateDetail.gc_name;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    STMGoodsCategoryDetail *cateDetail = self.cateArray[indexPath.row];
    NSString *selectGCid = cateDetail.gc_id;
    if (self.selectgcName) {
        self.selectgcName = [NSString stringWithFormat:@"%@%@",self.selectgcName,cateDetail.gc_name];
    } else {
        self.selectgcName = cateDetail.gc_name;
    }
    [STMNetworkAPI getOtherGoodsCategoryWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                      firstGCid:selectGCid
                                        success:^(STMGoodsCategoryModel *result) {
                                            if ([result.code isEqualToString:@"200"]) {
                                                self.cateArray = [NSMutableArray arrayWithArray:result.result];
                                                [self.cateTableView reloadData];
                                            } else if ([result.code isEqualToString:@"401"]) {
                                                [GlobalUtil presentLoginVC];
                                            } else {
                                                self.goodsCateLabel.textColor = [UIColor blackColor];
                                                self.goodsCateLabel.text = self.selectgcName;
                                                self.selectgcId = cateDetail.gc_id;
                                                [self cateTableViewDisappear];
                                            }
                                        }
                                        failure:^(NSError *err) {
                                            [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                        }];
}


- (void)submitButtonClick {
    if ([self.goodsNameTf.text isEqualToString:@""] || [self.goodsCateLabel.text isEqualToString:@"点击选择商品分类"] || [self.goodsPriceTf.text isEqualToString:@""] || [self.marketPriceTf.text isEqualToString:@""] || [self.goodsStoreTf.text isEqualToString:@""] || [self.goodsFreightTf.text isEqualToString:@""] || [self.goodsDescriptionTf.text isEqualToString:@""] || self.addImageView.imageDataArr.count == 0) {
        [GlobalUtil HUDShowMessage:@"请输入完整信息" addedToView:self.view];
        return;
    }
    if (self.goodsPriceTf.text.floatValue > self.marketPriceTf.text.floatValue) {
        [GlobalUtil HUDShowMessage:@"商品价格不能高于市场价" addedToView:self.view];
        return;
    }
    
    NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:self.addImageView.uploadImageNames];
    for (NSString *imageName in self.addImageView.uploadImageNames) {
        if ([imageName isEqualToString:@""]) {
            [tmpArray removeObject:imageName];
        }
    }
    if (self.addImageView.imageDataArr.count != tmpArray.count) {
        [GlobalUtil HUDShowMessage:@"图片上传中，请稍后" addedToView:self.view];
        return;
    }
    self.uploadImages = [tmpArray componentsJoinedByString:@","];
    [STMNetworkAPI publishGoodsWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                            imageNames:self.uploadImages
                             goodsName:self.goodsNameTf.text
                           goodsCateId:self.selectgcId
                         goodsCateName:self.goodsCateLabel.text
                            goodsPrice:self.goodsPriceTf.text
                           marketPrice:self.marketPriceTf.text
                            goodsStore:self.goodsStoreTf.text
                          goodsFreight:self.goodsFreightTf.text
                      goodsDescription:self.goodsDescriptionTf.text
                               success:^(STMLoginModel *result) {
                                   if ([result.code isEqualToString:@"200"]) {
                                       [[NSNotificationCenter defaultCenter] postNotificationName:nGoodsManagementRefresh object:nil];
                                       [GlobalUtil HUDShowMessage:result.message addedToView:self.navigationController.view];
                                       [self.navigationController popViewControllerAnimated:YES];
                                   } else if ([result.code isEqualToString:@"401"]) {
                                       STMLoginViewController *loginVC = [[STMLoginViewController alloc] init];
                                       [self.navigationController presentViewController:loginVC animated:YES completion:nil];
                                   } else {
                                       [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                   }
                               }
                               failure:^(NSError *err) {
                                   [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                               }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
